<template>
  <view class="container">
    <view class="example">
      <uni-forms ref="form" :model="audi" labelWidth="80px">
        <uni-forms-item label="姓名" name="name">
          <uni-easyinput v-model="audi.name" placeholder="请输入姓名" />
        </uni-forms-item>
        <uni-forms-item label="年龄" name="age">
          <uni-easyinput v-model="audi.age" placeholder="请输入年龄" />
        </uni-forms-item>
        <uni-forms-item label="性别" name="sex" required>
          <uni-data-checkbox v-model="audi.sex" :localdata="sexs" />
        </uni-forms-item>
        <uni-forms-item label="手机号码" name="tel">
          <uni-easyinput v-model="audi.tel" placeholder="请输入手机号码" />
        </uni-forms-item>
        <uni-forms-item label="证件号码" name="idcard">
          <uni-easyinput v-model="audi.idcard" placeholder="请输入身份证号码" />
        </uni-forms-item>
        <uni-forms-item label="现居城市" name="city">
          <uni-easyinput v-model="audi.city" placeholder="请输入现居城市" />
        </uni-forms-item>
      </uni-forms>
      <button type="primary" class="submit-button" @click="submit">提交</button>
    </view>
  </view>
</template>

<script>
import { getInfo } from '@/api/login'
import {
  getAudiProfile,
  addAudiProfile,
  updateAudiProfile,
  getAudiProfileByUserAndTv,
  updateAudiProfileByUserAndTv
} from "@/api/system/audi"
import storage from "@/utils/storage"
import constant from '@/utils/constant'

export default {
  data() {
    let openid = storage.get(constant.openid);
    let fansid = storage.get(constant.fansid);

    return {
      user: {}, // 存储用户信息
      audi: {
        name: "",
        age: "",
        sex: "",
        tel: "",
        idcard: "",
        city: "",
        status: 1,
        openid: openid,
        fans_id: fansid,
        tvId: "", // 初始化 tv_id
        id: "" // 初始化 id
      },
      sexs: [
        { text: '男', value: "0" },
        { text: '女', value: "1" },
        { text: '未知', value: "2" },
        { text: '跨性别', value: "3" }
      ],
      rules: {
        name: {
          rules: [
            { required: true, errorMessage: '用户昵称不能为空' }
          ]
        },
        tel: {
          rules: [
            { required: true, errorMessage: '手机号码不能为空' },
            { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, errorMessage: '请输入正确的手机号码' }
          ]
        },
        idcard: {
          rules: [
            { required: true, errorMessage: '身份证号码不能为空' },
            { pattern: /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[1-2]\d|30|31)\d{3}(\d|X)$/, errorMessage: '请输入正确的身份证号码' }
          ]
        }
      }
    }
  },
  onLoad(options) {
    this.loadUserInfo().then(() => {
      if (options.tvId) {
        this.audi.tvId = options.tvId; // 接收参数中的 tv_id
        //console.log('tv_id received:', this.audi.tv_id); // 调试日志
		this.audi.userId=this.user.userId;
        this.loadAudiData(options.tvId, this.user.userId);
      }
    });
  },
  onReady() {
    this.$refs.form.setRules(this.rules)
  },
  methods: {
    loadUserInfo() {
      return getInfo().then(response => {
        console.log(response);
        if (response.user) {
          this.user = response.user; // 保存用户信息
          console.log('用户信息:', this.user); // 调试日志
        }
      });
    },
    loadAudiData(tvId, userId) {
      getAudiProfileByUserAndTv(tvId, userId).then(response => {
        console.log('API response:', response); // 调试日志
        if (response && response.data) {
          // 确保响应数据结构与 audi 对象一致
          response.data.sex = "" + response.data.sex;
          this.audi = {
            name: response.data.name || "",
            age: response.data.age || "",
            sex: response.data.sex || "",
            tel: response.data.tel || "",
            idcard: response.data.idcard || "",
            city: response.data.city || "",
            status: response.data.status || 1,
            openid: response.data.openid || this.audi.openid,
            fans_id: response.data.fans_id || this.audi.fans_id,
            tvId: response.data.tvId || this.audi.tvId,
            id: response.data.id || "",
			userId: response.data.userId || this.user.userId
          };
          console.log(this.audi);
        } else {
          console.error('Invalid response structure:', response); // 调试日志
        }
      }).catch(error => {
        console.error('API call error:', error); // 错误日志
      });
    },
    submit(ref) {
      console.log('Form data before submission:', this.audi); // 调试日志
	  //this.audi.userId=this.audi.user_id;
	  //unset(this.audi.user_id);
      this.$refs.form.validate().then(res => {
        if (this.audi.id) {
          updateAudiProfileByUserAndTv(this.audi).then(response => {
            this.$modal.msgSuccess("修改成功")
            setTimeout(() => {
              this.$tab.reLaunch(`/pages/index`);
            }, 2000); // 2000毫秒（2秒）的延迟
          });
        } else {
          addAudiProfile(this.audi).then(response => {
            this.$modal.msgSuccess("新增成功")
            setTimeout(() => {
              this.$tab.reLaunch(`/pages/index`);
            }, 2000); // 2000毫秒（2秒）的延迟
          });
        }
      });
    }
  }
}
</script>

<style lang="scss">
.page {
  background-color: #ffffff;
}

.example {
  padding: 15px;
  background-color: #fff;
}

.segmented-control {
  margin-bottom: 15px;
}

.button-group {
  margin-top: 15px;
  display: flex;
  justify-content: space-around;
}

.form-item {
  display: flex;
  align-items: center;
  flex: 1;
}

.button {
  display: flex;
  align-items: center;
  height: 35px;
  line-height: 35px;
  margin-left: 10px;
}

.submit-button {
  background-color: #007aff;
  color: white;
  padding: 10px 20px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}
</style>
